﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using com.tiyma.common;
using com.tiyma.model;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Documents;
using System.Web;
using MySql.Data.MySqlClient;
namespace com.tiyma.components
{
    public class BookManager
    {
        /// <summary>
        /// 搜索小说
        /// </summary>
        /// <param name="i_key_word"></param>
        /// <param name="i_page_index"></param>
        /// <param name="i_page_size"></param>
        /// <param name="o_total_count"></param>
        /// <returns></returns>
        public List<BookInfo> SearchBook(string i_key_word,Consts.SearchType i_search_type, int i_page_index, int i_page_size, out int o_total_count)
        {
            o_total_count = 0;

            string t_search_field = "BOOKNAME_AUTHORNAME_BOOKCATEGORYNAME_BOOKSUBCATEGORYNAME";

            if (i_search_type == Consts.SearchType.AuthorName)
                t_search_field = "AUTHORNAME";

            if (i_search_type == Consts.SearchType.BookName)
                t_search_field = "BOOKNAME";

            if(i_search_type==Consts.SearchType.Category)
                t_search_field="BOOKCATEGORY";

            try
            {
                string t_index_path = AppConfig.BookIndexPath;

                if (string.IsNullOrEmpty(t_index_path) || !Directory.Exists(t_index_path))
                {
                    LogHelper.Info("搜索小说的目录不存在!");
                    return null;
                }

                DirectoryInfo t_root_dir = new DirectoryInfo(AppConfig.BookIndexPath);

                DirectoryInfo t_search_dir = null;

               List<DirectoryInfo> t_list_dir=new List<DirectoryInfo>();

                foreach (DirectoryInfo t_dir in t_root_dir.GetDirectories())
                {
                    t_list_dir.Add(t_dir);
                }

                if (t_list_dir.Count <= 0)
                    return null;

                if (t_list_dir.Count == 1)
                {
                    t_search_dir = t_list_dir[0];
                }
                else
                {
                    //按创建时间倒序
                    t_list_dir.Sort(delegate(DirectoryInfo t_a,DirectoryInfo t_b)
                        {
                            if (t_a.CreationTime < t_b.CreationTime)
                                return 1;
                            else if (t_a.CreationTime == t_b.CreationTime)
                                return 0;
                            return -1;
                        });
                    
                    t_search_dir = t_list_dir[0];

                   // 最近10分钟生成的不要
                    if (DateTime.Now.Subtract(t_search_dir.CreationTime).Minutes < 10)
                    {
                        t_search_dir = t_list_dir[1];
                    }
                }

                BooleanQuery t_bq = new BooleanQuery();

                QueryParser t_query_parse = new QueryParser(t_search_field, new Lucene.Net.Analysis.Standard.StandardAnalyzer());

                Query t_query = t_query_parse.Parse(i_key_word.Trim());
                t_bq.Add(t_query, BooleanClause.Occur.MUST);

       

                IndexSearcher t_seo = new IndexSearcher(Path.Combine(AppConfig.BookIndexPath,t_search_dir.Name));

                Hits t_hits = t_seo.Search(t_bq);

                o_total_count = t_hits.Length();

                if (o_total_count == 0)
                {
                    LogHelper.Info(string.Format("从seo路径：{0}搜索关键字：{1}得到0条记录", Path.Combine(AppConfig.BookIndexPath, t_search_dir.Name), i_key_word));
                }

                List<BookInfo> t_list = new List<BookInfo>();

                int t_site_id = 1;

                BookInfo t_book = null;

                for (int index = (i_page_index - 1) * i_page_size; index < o_total_count && index < (i_page_index * i_page_size + 1); index++)
                {
                    Document t_doc = t_hits.Doc(index);

                    t_book = new BookInfo();

                    t_book.BookId = t_doc.Get("BOOKID");
                    t_book.BookName = t_doc.Get("BOOKNAME");
                    t_book.AuthorName = t_doc.Get("AUTHORNAME");
                    t_book.BookCategory = t_doc.Get("BOOKCATEGORY");
                    t_book.BookSubCategory = t_doc.Get("BOOKSUBCATEGORYNAME");
                    t_book.Description = t_doc.Get("DESCRIPTION");
                    t_book.LastUpdateChapterId = t_doc.Get("LASTUPDATECHAPTERID");
                    t_book.LastUpdateChapterName = t_doc.Get("LASTUPDATECHAPTERNAME");
                    t_book.LastUpdateTime = DateTime.Parse(t_doc.Get("LASTUPDATETIME"));
                  
                    if (!int.TryParse(t_doc.Get("SITEID"), out t_site_id))
                        t_site_id = 1;
                    t_book.SiteId = t_site_id;
                    t_book.SiteName = Consts.GetSiteName(t_book.SiteId);
                    t_list.Add(t_book);
                }

                return t_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("搜索小说失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 获取长点的小说章节信息
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_site_id"></param>
        /// <returns></returns>
        public DataSet GetBookChapter(string i_book_id, int i_site_id)
        {

            string t_str_sql = string.Empty;

            try
            {
              
                string t_table_name=Consts.GetTableName(i_site_id);

                if (string.IsNullOrEmpty(t_table_name))
                {
                    LogHelper.Info(string.Format("获取站点{0}的数据表名失败", i_site_id));
                    return null;
                }

                t_str_sql = string.Format("select chapterId,chapterName,updateTime,chapterUrl,siteId from tb{0} where bookId='{1}' order by updatetime", t_table_name, i_book_id);

                return DBManager.Query(t_str_sql);
                
            }
            catch (Exception ex)
            {
                LogHelper.Error("查询小说信息失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 获取章节信息
        /// </summary>
        /// <param name="i_chapter_id"></param>
        /// <param name="i_site_id"></param>
        /// <returns></returns>
        public ChapterInfo GetChapterInfo(string i_chapter_id, int i_site_id)
        {
             string t_table_name=Consts.GetTableName(i_site_id);

            if (string.IsNullOrEmpty(t_table_name))
            {
                LogHelper.Info(string.Format("获取站点{0}的数据表名失败", i_site_id));
                return null;
            }
            string t_str_sql = string.Format("select bookId, preChapterId,nextChapterId,chapterName,chapterUrl from tb{0} b where chapterId='{1}'",
                t_table_name, i_chapter_id);

            try
            {
                ChapterInfo t_chapter = new ChapterInfo();

                using (MySqlDataReader t_reader = DBManager.ExecuteReader(t_str_sql))
                {
                    while (t_reader.Read())
                    {
            
                        t_chapter.PreChapterId = t_reader["preChapterId"].ToString();
                        t_chapter.NextChapterId = t_reader["nextChapterId"].ToString();
                        t_chapter.ChapterName = t_reader["chapterName"].ToString();
                        t_chapter.ChapterUrl = t_reader["chapterUrl"].ToString();
                        t_chapter.BookId = t_reader["bookId"].ToString();
                        t_chapter.ChapterId = i_chapter_id;

                    }
                }

                return t_chapter;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取章节信息失败" + ex.ToString());
                return null;
            }
        }

        /// <summary>
        /// 获取热门搜索
        /// </summary>
        /// <param name="o_author_list"></param>
        /// <returns></returns>
        public List<string> GetTopSearch(out List<string> o_author_list)
        {
            string t_str_sql = "select top 8 bookName,bookAuthorName from tbbook order by lastupdatetime desc";
            o_author_list = null;
            List<string> t_book_name_list = null;
            string t_book_key = "book_cache";
            string t_author_key = "author_cache";

            if (HttpContext.Current != null && HttpContext.Current.Cache[t_book_key] != null)
            {
                t_book_name_list = HttpContext.Current.Cache[t_book_key] as List<string>;
               
            }

            if (HttpContext.Current != null && HttpContext.Current.Cache[t_author_key] != null)
            {
                o_author_list = HttpContext.Current.Cache[t_author_key] as List<string>;

            }

            if (t_book_name_list == null && o_author_list!=null)
            {
                return t_book_name_list;     
            }

            try
            {
                using (MySqlDataReader t_reader = DBManager.ExecuteReader(t_str_sql))
                {

                    t_book_name_list = new List<string>();
                    o_author_list = new List<string>();
                    while (t_reader.Read())
                    {
                        t_book_name_list.Add(t_reader["bookName"].ToString());
                        o_author_list.Add(t_reader["bookAuthorName"].ToString());
                    }
                }
                HttpContext.Current.Cache.Insert(t_book_key, t_book_name_list, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
                HttpContext.Current.Cache.Insert(t_author_key, o_author_list, null, DateTime.Now.AddDays(1), TimeSpan.Zero);
                return t_book_name_list;
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取搜索热门关键字失败" + ex.ToString());
                return null;
            }
        }
    }
}
